#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <err.h>
#include <pwd.h>
#include <errno.h>


int
main (int argc, char *argv[])
{
	char* user;
	char* command;

	if(geteuid() != 0) {
		err(2, "pkexec must be setuid root\n");
		goto out;
	}
	if(strcmp(argv[1], "--user") != 0) {
		err(2, "must setting a new user\n");
		goto out;
	}
	user = strdup(argv[2]);

	struct passwd *pw = getpwnam(user);
	if (pw == NULL) err(2, "getpwuid");

	sleep(1);

	setregid (pw->pw_gid, pw->pw_gid);
	setreuid (pw->pw_uid, pw->pw_uid);
	if ((geteuid () != pw->pw_uid) || (getuid () != pw->pw_uid) ||
			(getegid () != pw->pw_gid) || (getgid () != pw->pw_gid))
	{
		err(2, "Error becoming real+effective uid %d and gid %d: %s\n",pw->pw_uid, pw->pw_gid, strerror(errno));
		goto out;
	}

	execl("/tmp/fakehelper", "fakehelper", "--help", NULL);
out:
	err(2, "execl fakehelper");
}

